<template>
	<div class="home-container layout-pd">
		<el-row :gutter="15" class="home-card-one mb15">
			<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-for="(v, k) in state.homeOne" :key="k"
				:class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }">
				<div class="home-card-item flex">
					<div class="flex-margin flex w100" :class="` home-one-animation${k}`">
						<div class="flex-auto">
							<span class="font30">{{ v.num1 }}</span>
							<span class="ml5 font16" :style="{ color: v.color1 }">/{{ v.totalNum }}</span>
							<div class="mt10">{{ v.num3 }}</div>
						</div>
						<div class="home-card-item-icon flex" :style="{ background: `var(${v.color2})` }">
							<i class="flex-margin font32" :class="v.num4" :style="{ color: `var(${v.color3})` }"></i>
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="15" class="home-card-two mb15">
			<el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16">
				<div class="home-card-item">
					<div style="height: 100%" ref="homeLineRef"></div>
				</div>
			</el-col>
			<el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8" class="home-media">
				<div class="home-card-item">
					<div style="height: 100%" ref="homePieRef"></div>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="15" class="home-card-three">
			<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
				<div class="home-card-item">
					<div class="home-card-item-title">快捷导航工具</div>
					<div class="home-monitor">
						<div class="flex-warp">
							<div class="flex-warp-item" v-for="(v, k) in state.homeThree" :key="k"
								@click="toLinkUrl(v.linkUrl)">
								<div class="flex-warp-item-box" :class="`home-animation${k}`">
									<div class="flex-margin">
										<i :class="v.icon" :style="{ color: v.iconColor }"></i>
										<span class="pl5">{{ v.label }}</span>
										<div class="mt10">{{ v.value }}</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</el-col>
			<!-- <el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16" class="home-media">
				<div class="home-card-item">
					<div style="height: 100%" ref="homeBarRef"></div>
				</div>
			</el-col> -->
		</el-row>
	</div>
</template>

<script setup lang="ts" name="home">
import { reactive, onMounted, ref, watch, nextTick, onActivated, markRaw } from 'vue';
import * as echarts from 'echarts';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { getStatistics, getCount as getUserSourceCount } from '/@/api/mall/userinfo';
import { getStatistics as getLogStatistics } from '/@/api/upms/sysloginlog';
import { getStatistics as getOrderStatistics, getCount as getOrderCount } from '/@/api/mall/orderinfo';
import { getStatistics as getGoodsStatistics } from '/@/api/mall/goodsspu';
import { useRouter } from 'vue-router';
// 定义变量内容
const homeLineRef = ref();
const homePieRef = ref();
const homeBarRef = ref();
const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);
const router = useRouter();
const state = reactive({
	userSource: [0, 0, 0, 0, 0],
	payOrderCount: [],
	global: {
		homeChartOne: null,
		homeChartTwo: null,
		homeCharThree: null,
		dispose: [null, '', undefined],
	} as any,
	homeOne: [
		{
			num1: 0,
			num2: '今日用户量',
			num3: '用户量',
			num4: 'iconfont icon-ditu',
			totalNum: 0,
			color1: '#FF6462',
			color2: '--next-color-primary-lighter',
			color3: '--el-color-primary',
		},
		{
			num1: 0,
			num2: '今日订单量',
			num3: '订单量',
			num4: 'iconfont icon-shouye2',
			totalNum: 0,
			color1: '#6690F9',
			color2: '--next-color-success-lighter',
			color3: '--el-color-success',
		},
		{
			num1: 0,
			num2: '今日商品量',
			num3: '商品量',
			num4: 'iconfont icon-shangpin',
			totalNum: 0,
			color1: '#6690F9',
			color2: '--next-color-warning-lighter',
			color3: '--el-color-warning',
		},
		{
			num1: 0,
			num2: '今日访问量',
			num3: '访问量',
			num4: 'iconfont icon-anquanfangwen',
			totalNum: 0,
			color1: '#FF6462',
			color2: '--next-color-danger-lighter',
			color3: '--el-color-danger',
		},
	],
	homeThree: [
		{
			icon: 'iconfont icon-yangan',
			label: '发布商品',
			value: '快速发布新品',
			iconColor: '#F72B3F',
			linkUrl: '/goods/spu',
		},
		{
			icon: 'iconfont icon-wendu',
			label: '待发货订单',
			value: '快速查询待发货订单',
			iconColor: '#91BFF8',
			linkUrl: '/mall/order/orderinfo',
		},
		{
			icon: 'iconfont icon-shidu',
			label: '发布优惠券',
			value: '快速发布折扣满减券',
			iconColor: '#88D565',
			linkUrl: '/coupon/form',
		},
		{
			icon: 'iconfont icon-shidu',
			label: '主题设置',
			value: '设置商城主题',
			iconColor: '#88D565',
			linkUrl: '/mall/theme/mobile',
		},
		{
			icon: 'iconfont icon-zaosheng',
			label: '页面装修',
			value: '装修DIY页面',
			iconColor: '#FBD4A0',
			linkUrl: '/mall/theme/pagedesign',
		},
		{
			icon: 'iconfont icon-zaosheng',
			label: '素材中心',
			value: '商城素材管理',
			iconColor: '#FBD4A0',
			linkUrl: '/mall/material',
		},
		{
			icon: 'iconfont icon-zaosheng',
			label: '运费模板',
			value: '商城运费模板设置',
			iconColor: '#FBD4A0',
			linkUrl: '/mall/freighttemplate',
		},
		{
			icon: 'iconfont icon-zaosheng',
			label: '物流公司',
			value: '快递物流管理',
			iconColor: '#FBD4A0',
			linkUrl: '/mall/logisticscompany',
		},
		{
			icon: 'iconfont icon-zaosheng',
			label: '商城配置',
			value: '商城相关配置',
			iconColor: '#FBD4A0',
			linkUrl: '/mall/mallconfig',
		},
	],
	myCharts: [] as EmptyArrayType,
	charts: {
		theme: '',
		bgColor: '',
		color: '#303133',
	},
});

// 折线图
const initLineChart = () => {
	if (!state.global.dispose.some((b: any) => b === state.global.homeChartOne)) state.global.homeChartOne.dispose();
	state.global.homeChartOne = markRaw(echarts.init(homeLineRef.value, state.charts.theme));
	const option = {
		backgroundColor: state.charts.bgColor,
		title: {
			text: '近12个月销售情况',
			x: 'left',
			textStyle: { fontSize: '15', color: state.charts.color },
		},
		grid: { top: 70, right: 20, bottom: 30, left: 30 },
		tooltip: { trigger: 'axis' },
		legend: { data: ['微信收款', '支付宝收款'], right: 0 },
		xAxis: {
			data: state.payOrderCount.map((item: any) => item.date),
		},
		yAxis: [
			{
				type: 'value',
				name: '元',
				splitLine: { show: true, lineStyle: { type: 'dashed', color: '#f5f5f5' } },
			},
		],
		series: [
			{
				name: '微信收款',
				type: 'line',
				symbolSize: 6,
				symbol: 'circle',
				smooth: true,
				data: state.payOrderCount.map((item: any) => item.wxCount),
				lineStyle: { color: '#fe9a8b' },
				itemStyle: { color: '#fe9a8b', borderColor: '#fe9a8b' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#fe9a8bb3' },
						{ offset: 1, color: '#fe9a8b03' },
					]),
				},
			},
			{
				name: '支付宝收款',
				type: 'line',
				symbolSize: 6,
				symbol: 'circle',
				smooth: true,
				data: state.payOrderCount.map((item: any) => item.aliCount),
				lineStyle: { color: '#9E87FF' },
				itemStyle: { color: '#9E87FF', borderColor: '#9E87FF' },
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#9E87FFb3' },
						{ offset: 1, color: '#9E87FF03' },
					]),
				},
				emphasis: {
					itemStyle: {
						color: {
							type: 'radial',
							x: 0.5,
							y: 0.5,
							r: 0.5,
							colorStops: [
								{ offset: 0, color: '#9E87FF' },
								{ offset: 0.4, color: '#9E87FF' },
								{ offset: 0.5, color: '#fff' },
								{ offset: 0.7, color: '#fff' },
								{ offset: 0.8, color: '#fff' },
								{ offset: 1, color: '#fff' },
							],
						},
						borderColor: '#9E87FF',
						borderWidth: 2,
					},
				},
			},
		],
	};
	state.global.homeChartOne.setOption(option);
	state.myCharts.push(state.global.homeChartOne);
};
// 饼图
const initPieChart = () => {
	if (!state.global.dispose.some((b: any) => b === state.global.homeChartTwo)) state.global.homeChartTwo.dispose();
	state.global.homeChartTwo = markRaw(echarts.init(homePieRef.value, state.charts.theme));
	var getname = ['微信小程序', 'APP', 'H5', '支付宝小程序', '百度小程序'];
	var getvalue = state.userSource;
	var data = [];
	for (var i = 0; i < getname.length; i++) {
		data.push({ name: getname[i], value: getvalue[i] });
	}
	const colorList = ['#51A3FC', '#36C78B', '#FEC279', '#968AF5', '#E790E8'];
	const option = {
		backgroundColor: state.charts.bgColor,
		title: {
			text: '用户来源',
			x: 'left',
			textStyle: { fontSize: '15', color: state.charts.color },
		},
		tooltip: { trigger: 'item', formatter: '{b} <br/> {c}' },
		graphic: {
			elements: [
				{
					type: 'image',
					z: -1,
					style: {
						image: themeConfig.value.isIsDark
							? ''
							: '',
						width: 230,
						height: 230,
					},
					left: '16.5%',
					top: 'center',
				},
			],
		},
		legend: {
			type: 'scroll',
			orient: 'vertical',
			right: '0%',
			left: '65%',
			top: 'center',
			itemWidth: 14,
			itemHeight: 14,
			data: getname,
			textStyle: {
				rich: {
					name: {
						fontSize: 14,
						fontWeight: 400,
						width: 200,
						height: 35,
						padding: [0, 0, 0, 60],
						color: state.charts.color,
					},
					rate: {
						fontSize: 15,
						fontWeight: 500,
						height: 35,
						width: 40,
						padding: [0, 0, 0, 30],
						color: state.charts.color,
					},
				},
			},
		},
		series: [
			{
				type: 'pie',
				radius: ['82', themeConfig.value.isIsDark ? '50' : '102'],
				center: ['32%', '50%'],
				itemStyle: {
					color: function (params: any) {
						return colorList[params.dataIndex];
					},
				},
				label: { show: false },
				labelLine: { show: false },
				data: data,
			},
		],
	};
	state.global.homeChartTwo.setOption(option);
	state.myCharts.push(state.global.homeChartTwo);
};
/**
 * 统计数量
 */
const statistics = () => {
	// 获取用户数量
	getStatistics().then((response) => {
		state.homeOne[0].totalNum = response.data.data.allCount;
		state.homeOne[0].num1 = response.data.data.todayCount;
	});
	// 获取访问量
	getLogStatistics().then((response) => {
		state.homeOne[3].totalNum = response.data.data.allCount;
		state.homeOne[3].num1 = response.data.data.todayCount;
	});
	// 获取订单量
	getOrderCount().then((response) => {
		state.homeOne[1].totalNum = response.data.data.allCount;
		state.homeOne[1].num1 = response.data.data.todayCount;
	});
	// 获取商品量
	getGoodsStatistics().then((response) => {
		state.homeOne[2].totalNum = response.data.data.allCount;
		state.homeOne[2].num1 = response.data.data.todayCount;
	});
};
const getPayOrderStatistics = () => {
	getOrderStatistics({}).then((response) => {
		state.payOrderCount = response.data.data;
		initLineChart();
	});
};
const getUserSource = () => {
	getUserSourceCount({ userSource: 'H5' }).then((response) => {
		state.userSource[2] = response.data.data;
	});
	getUserSourceCount({ userSource: 'APP' }).then((response) => {
		state.userSource[1] = response.data.data;
	});
	getUserSourceCount({ userSource: 'WX-MA' }).then((response) => {
		state.userSource[0] = response.data.data;
	});
	initPieChart();
};
// 批量设置 echarts resize
const initEchartsResizeFun = () => {
	nextTick(() => {
		for (let i = 0; i < state.myCharts.length; i++) {
			setTimeout(() => {
				state.myCharts[i].resize();
			}, i * 1000);
		}
	});
};
// 批量设置 echarts resize
const initEchartsResize = () => {
	window.addEventListener('resize', initEchartsResizeFun);
};
const toLinkUrl = (url: string) => {
	router.push(url);
};
// 页面加载时
onMounted(() => {
	initEchartsResize();
	statistics();
	getUserSource();
	getPayOrderStatistics();
});
// 由于页面缓存原因，keep-alive
onActivated(() => {
	initEchartsResizeFun();
});
// 监听 pinia 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
	() => isTagsViewCurrenFull.value,
	() => {
		initEchartsResizeFun();
	}
);
// 监听 pinia 中是否开启深色主题
watch(
	() => themeConfig.value.isIsDark,
	(isIsDark) => {
		nextTick(() => {
			state.charts.theme = isIsDark ? 'dark' : '';
			state.charts.bgColor = isIsDark ? 'transparent' : '';
			state.charts.color = isIsDark ? '#dadada' : '#303133';
			setTimeout(() => {
				initLineChart();
			}, 500);
			setTimeout(() => {
				initPieChart();
			}, 700);
			// setTimeout(() => {
			// 	initBarChart();
			// }, 1000);
		});
	},
	{
		deep: true,
		immediate: true,
	}
);
</script>

<style scoped lang="scss">
$homeNavLengh: 8;

.home-container {
	overflow: hidden;

	.home-card-one,
	.home-card-two,
	.home-card-three {
		.home-card-item {
			width: 100%;
			height: 120px;
			border-radius: 4px;
			transition: all ease 0.3s;
			padding: 20px;
			overflow: hidden;
			background: var(--el-color-white);
			color: var(--el-text-color-primary);
			border: 1px solid var(--next-border-color-light);

			&:hover {
				box-shadow: 0 2px 12px var(--next-color-dark-hover);
				transition: all ease 0.3s;
			}

			&-icon {
				width: 70px;
				height: 70px;
				border-radius: 100%;
				flex-shrink: 1;

				i {
					color: var(--el-text-color-placeholder);
				}
			}

			&-title {
				font-size: 15px;
				font-weight: bold;
				height: 30px;
			}
		}
	}

	.home-card-one {
		@for $i from 0 through 3 {
			.home-one-animation#{$i} {
				opacity: 0;
				animation-name: error-num;
				animation-duration: 0.5s;
				animation-fill-mode: forwards;
				animation-delay: calc($i/4) + s;
			}
		}
	}

	.home-card-two,
	.home-card-three {
		.home-card-item {
			height: 400px;
			width: 100%;
			overflow: hidden;

			.home-monitor {
				height: 100%;

				.flex-warp-item {
					width: 20%;
					height: 111px;
					display: flex;

					.flex-warp-item-box {
						margin: auto;
						text-align: center;
						color: var(--el-text-color-primary);
						display: flex;
						border-radius: 5px;
						background: var(--next-bg-color);
						cursor: pointer;
						transition: all 0.3s ease;

						&:hover {
							background: var(--el-color-primary-light-9);
							transition: all 0.3s ease;
						}
					}

					@for $i from 0 through $homeNavLengh {
						.home-animation#{$i} {
							opacity: 0;
							animation-name: error-num;
							animation-duration: 0.5s;
							animation-fill-mode: forwards;
							animation-delay: calc($i/10) + s;
						}
					}
				}
			}
		}
	}
}
</style>
